package com.clz.appdesign.appdependence.net.updatebyrx2;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;

/**
 * 基于此修改
 * https://github.com/shanyao0/DownLoadManager\
 */
public class UpdateManager {
    private long timeRange;
    private static UpdateManager instance;
    private UpdateDialog dialog;
    private TextView tvRightTxt;
    private UpdateManager() {
    }

    public synchronized static UpdateManager getInstance(){
        if (instance == null) {
            instance = new UpdateManager();
        }
        return instance;
    }
    public TextView getRightText(){
        return tvRightTxt;
    }
    /**
     * 显示更新对话框
     */
    public void showUpdateDialog(final String url, final Context mContext) {

        dialog = new UpdateDialog(mContext);
        tvRightTxt=dialog.getRightText();
        dialog.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //防抖动,两次点击间隔小于500ms都return;
                if (System.currentTimeMillis() - timeRange < 500) {
                    return;
                }
                dialog.setProgressVisiable(true);
                timeRange = System.currentTimeMillis();

                dialog.setRightText("正在下载");
                dialog.setRightEnable(false);
                LogUtils.iTag("update1",url);
                //启动下载服务
                Intent intent = new Intent(mContext, DownLoadService.class);
                intent.putExtra("url",url);
                mContext.startService(intent);
            }
        });

        dialog.show();
    }

    /**
     * 更新进度条
     * @param progress
     */
    public void updateProgress(int progress){
        if (dialog == null || !dialog.isShowing()||progress <= 0) {
            LogUtils.i("updateProgress","dialog为空或NoShowing");
            return;
        }
        dialog.setProgress(progress);
    }

    /**
     * 完成下载
     */
    public void finsh(){

        if (dialog == null || dialog.isShowing()) {
            return;
        }
        dialog.dismiss();
        //把当前工具类 置空 ，防止updateManager 在loginActivity 关闭后 再次打开时 activity 是新的
        //而 updateManager 中 mContext 还是之前loginActivity的mContext 导致dialog 无法show出来而报错
        instance = null;
    }

    /**
     * 重试
     */
    public void retry(){
        if (dialog == null || !dialog.isShowing()) {
            return;
        }
        dialog.setRightText("重试");
        dialog.setRightEnable(true);
    }
}